var name,background,musichost;
function getUrlParmsByStr(name,str){
   var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
   var r = str.match(reg);
   if(r!=null)
   return unescape(r[2]);
   return null;
   }
// var id = getUrlParms("id");
window.onload=function(){
	background = chrome.extension.getBackgroundPage();
	//console.log(background);
	document.getElementById("down").onclick = function(){
		//console.log(background.url);
		switch (musichost) {
			case "baidu":
			
			//console.log(decodeURI(background.url));
			//background.match(/link\S*d(\S*)ff/);
			//console.log("百度");
			var link = getUrlParmsByStr("link",decodeURI(background.url));
			//console.log(link);
			background.url=link;
			break;
		}
		chrome.downloads.download(
		    {
		      url: background.url,
		      filename: "MUS/"+name+".mp3",
		      saveAs: true,
		      conflictAction: "uniquify"
		    }
	 	)
	}
	document.getElementById("check").onclick = function(){
		getCurrentTabId(function(tabId){
			chrome.tabs.executeScript(tabId, {file: '/js/content_scripts.js'});
		});
	}
}
// document.getElementById("qmkg-link").onclick = function(){
//     window.open("http://kg.qq.com/");
// }

function getCurrentTabId(callback)
{
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
    {
        if(callback) callback(tabs.length ? tabs[0].id: null);
    });
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
{
	if(request.musicName){
  		//name = request.musicName;
  		//musichost = request.musicHost;
  		//document.getElementById("down").style.display = 'block';
  		document.getElementById("title").style.display = 'block';
  		document.getElementById("title").innerText = "操作完成";
  		//document.getElementById("check").style.display = "none";
	}else {
		document.getElementById("title").style.display = 'block';
		document.getElementById("title").innerText = "操作失败"
	}
});